<template>
	<div class="padding20">
		<el-row style="margin-bottom: 7px">
			<el-form v-if="searchController" :inline="true" :model="queryForm" @submit.native.prevent @keyup.enter.native="queryList">
				<el-form-item>
					<el-input prefix-icon="el-icon-search" v-model="queryForm.smtp" autocomplete="off" placeholder="请输入邮箱SMTP地址" clearable></el-input>
				</el-form-item>

				<el-form-item>
					<el-input prefix-icon="el-icon-search" v-model="queryForm.mail" autocomplete="off" placeholder="请输入邮箱账号" clearable></el-input>
				</el-form-item>

				<el-form-item v-show="collapse.flag">
					<fortress-select v-model="queryForm.status" :dictList="YesNoList" placeholder="请选择启用状态" clearable filterable></fortress-select>
				</el-form-item>
				<el-form-item>
					<el-button type="primary" size="medium" icon="el-icon-search" @click="queryList({ current: 1 })">查询</el-button>
				</el-form-item>
				<el-form-item>
					<el-button type="primary" size="medium" icon="el-icon-refresh-left" @click="resetQueryForm">重置</el-button>
				</el-form-item>
				<el-form-item>
					<el-button type="text" @click="handleCollapseState">
						{{ collapse.label }}
						<i :class="collapse.icon"></i>
					</el-button>
				</el-form-item>
			</el-form>
			<el-button type="primary" size="medium" icon="el-icon-plus" v-if="$tools.hasPermission('message:mail:castleConfigMail:save')" @click="handleEdit()">添加</el-button>
			<el-button v-if="$tools.hasPermission('message:mail:castleConfigMail:deleteBatch')" size="medium" type="danger" icon="el-icon-delete" @click="handleDeleteBatch()">删除</el-button>
			<div style="float: right; padding-right: 17px">
				<el-tooltip class="item" effect="dark" :content="searchTips" placement="top">
					<i class="el-icon-search" style="margin-right: 10px; cursor: pointer" @click="handlesearch"></i>
				</el-tooltip>
				<el-tooltip class="item" effect="dark" content="导出文件" placement="top">
					<i class="el-icon-download" style="margin-right: 10px; cursor: pointer" @click="handleExport"></i>
				</el-tooltip>
				<el-tooltip class="item" effect="dark" content="刷新" placement="top">
					<i class="el-icon-refresh" style="margin-right: 10px; cursor: pointer" @click="refresh"></i>
				</el-tooltip>
				<el-tooltip class="item" effect="dark" content="列展示" placement="top">
					<el-popover placement="bottom" width="180" trigger="click" title="列展示" popper-class="columnShows">
						<el-checkbox-group v-model="tableShowList">
							<el-checkbox v-for="item in tableList" :label="item.propName" :key="item.propName" :value="item.propName">{{ item.propDesc }}</el-checkbox>
						</el-checkbox-group>
						<i slot="reference" class="el-icon-s-operation" style="cursor: pointer"></i>
					</el-popover>
				</el-tooltip>
			</div>
		</el-row>
		<el-table ref="multipleTable" :data="tableData" style="width: 100%; margin-bottom: 20px" row-key="id" border>
			<el-table-column type="selection" width="55" show-overflow-tooltip></el-table-column>
			<el-table-column v-if="$tools.isShow('code', tableShowList)" prop="code" label="编码" :show-overflow-tooltip="true"></el-table-column>
			<el-table-column v-if="$tools.isShow('smtp', tableShowList)" prop="smtp" label="邮箱SMTP地址" :show-overflow-tooltip="true"></el-table-column>
			<el-table-column v-if="$tools.isShow('port', tableShowList)" prop="port" label="端口号" :show-overflow-tooltip="true"></el-table-column>
			<el-table-column v-if="$tools.isShow('mail', tableShowList)" prop="mail" label="邮箱账号" :show-overflow-tooltip="true"></el-table-column>
			<el-table-column v-if="$tools.isShow('password', tableShowList)" prop="password" label="邮箱密码" :show-overflow-tooltip="true"></el-table-column>
			<el-table-column v-if="$tools.isShow('nickName', tableShowList)" prop="nickName" label="邮箱昵称" :show-overflow-tooltip="true"></el-table-column>
			<el-table-column v-if="$tools.isShow('status', tableShowList)" prop="status" label="状态" :show-overflow-tooltip="true">
				<template slot-scope="scope">
					<el-tag type="success" size="mini" v-if="scope.row.status == 1">已启用</el-tag>
					<el-tag type="danger" size="mini" v-else>未启用</el-tag>
				</template>
			</el-table-column>
			<el-table-column label="操作" fixed="right" min-width="180">
				<template slot-scope="scope">
					<el-button v-if="$tools.hasPermission('message:mail:castleConfigMail:info')" size="mini" plain @click="handleInfo(scope.row.id)">详情</el-button>
					<el-button v-if="$tools.hasPermission('message:mail:castleConfigMail:edit')" size="mini" plain @click="handleEdit(scope.row.id)">编辑</el-button>
					<el-button v-if="$tools.hasPermission('message:mail:castleConfigMail:edit')" size="mini" plain @click="handleDebug(scope.row.code)">调试</el-button>
					<el-button v-if="$tools.hasPermission('message:mail:castleConfigMail:delete')" size="mini" plain type="danger" @click="handleDelete(scope.row)">删除</el-button>
				</template>
			</el-table-column>
		</el-table>
		<pagination :total="page.total" :current-page="page.current" :page-size="page.size" @refreshData="queryList"></pagination>
		<!-- 新增、编辑 -->
		<form-edit v-if="formEditVisible" ref="formEdit" @refreshData="queryList"></form-edit>
		<!-- 详情 -->
		<form-info v-if="formInfoVisible" ref="formInfo"></form-info>

		<el-dialog :visible.sync="debug.visible" append-to-body modal-append-to-body>
			<el-form label-width="100px">
				<el-form-item label="标题" prop="subject">
					<el-input placeholder="请输入标题" clearable v-model="debug.formData.subject"></el-input>
				</el-form-item>
				<el-form-item label="接收人" prop="toUser">
					<el-tag class="el-tag" :key="tag + index" v-for="(tag, index) in debug.formData.toUser" closable :disable-transitions="false" @close="handleUserClose(tag)">
						{{ tag }}
					</el-tag>
					<el-input class="input-new-tag" v-if="debug.userVisible" v-model="debug.userValue" ref="saveTagInput" size="small" @keyup.enter.native="handleUserInputConfirm" @blur="handleUserInputConfirm"></el-input>
					<el-button v-else class="button-new-tag" size="small" @click="showUserInput">+ 请添加接收人</el-button>
				</el-form-item>
				<el-form-item label="抄送人" prop="toCCUser">
					<el-tag class="el-tag" :key="tag + index" v-for="(tag, index) in debug.formData.toCCUser" closable :disable-transitions="false" @close="handleCCUserClose(tag)">
						{{ tag }}
					</el-tag>
					<el-input class="input-new-tag" v-if="debug.ccUserVisible" v-model="debug.ccUserValue" ref="saveTagInput" size="small" @keyup.enter.native="handleCCUserInputConfirm" @blur="handleCCUserInputConfirm"></el-input>
					<el-button v-else class="button-new-tag" size="small" @click="showCCUserInput">+ 请添加抄送人</el-button>
				</el-form-item>
				<el-form-item label="邮件内容" prop="body">
					<fortress-editor v-model="debug.formData.body"></fortress-editor>
				</el-form-item>
				<el-form-item label="文件" prop="file">
					<fortress-upload type="file" :limit="99" multiple name="file" :formData="debug.formData"></fortress-upload>
				</el-form-item>
			</el-form>

			<template #footer>
				<el-button type="danger" @click="cancelDeBug">取消</el-button>
				<el-button type="success" @click="confirmDeBug" :loading="loading">确认发送</el-button>
			</template>
		</el-dialog>
	</div>
</template>
<script>
import { castleconfigmailPage, castleconfigmailDel, castleconfigmailDelBatch, castleconfigmailDynamicExport, mailDebug } from "@/api/message/mail/castleconfigmail.js"
import { viewTableList } from "@/api/public.api.js"
import FormEdit from "./castleconfigmail-edit"
import FormInfo from "./castleconfigmail-info"
import FortressPagination from "@/components/fortress-pagination.vue"
import { enumList } from "@/api/public.api.js"
export default {
	data() {
		return {
			tableData: [],
			formEditVisible: false,
			formInfoVisible: false,
			queryForm: {
				smtp: "",
				mail: "",
				status: "",
			},
			page: {
				current: 1,
				size: 10,
				total: 0,
			},
			collapse: {
				icon: "el-icon-arrow-down el-icon--right",
				label: "展开",
				flag: false,
			},
			tableList: [],
			tableShowList: [],
			YesNoList: [],
			searchTips: "显示搜索",
			searchController: false, //搜索显示控制

			debug: {
				visible: false,
				formData: {
					code: "",
					subject: "",
					toUser: [],
					toCCUser: [],
					body: "",
					file: [],
				},
				userVisible: false,
				userValue: "",
				ccUserVisible: false,
				ccUserValue: "",
			},
			loading: false,
		}
	},
	components: {
		"form-edit": FormEdit,
		"form-info": FormInfo,
		pagination: FortressPagination,
	},
	created() {
		this.queryEnumList()
		this.initTableList()
		this.queryList()
	},
	methods: {
		//搜索控制
		handlesearch() {
			this.searchController = !this.searchController
			if (this.searchController) {
				this.searchTips = "隐藏搜索"
			} else {
				this.searchTips = "显示搜索"
			}
		},
		queryEnumList() {
			this.YesNoList = []
			enumList("YesNo", "").then(resp => {
				if (resp.code == 0) {
					this.YesNoList = resp.data
				}
			})
		},
		refresh() {
			this.tableData = []
			this.queryList({ current: 1 })
		},
		//查询表格数据
		queryList(page) {
			if (page) {
				this.page.current = page.current ? page.current : this.page.current
				this.page.size = page.size ? page.size : this.page.size
			}
			this.queryForm.current = this.page.current
			this.queryForm.size = this.page.size
			castleconfigmailPage(this.queryForm).then(resp => {
				if (resp.code == 0) {
					this.tableData = resp.data.records
					this.page.total = resp.data.total
					//查询页大于总页数，重新查询
					let cu = this.page.total % this.page.size == 0 ? parseInt(this.page.total / this.page.size) : parseInt(this.page.total / this.page.size + 1)
					if (cu > 0 && this.page.current > cu) {
						this.queryList({ current: cu })
					}
				} else {
					this.$msg({
						message: resp.msg,
						type: "error",
					})
				}
			})
		},
		//打开编辑窗口
		handleEdit(id) {
			this.formEditVisible = true
			this.$nextTick(() => {
				this.$refs.formEdit.init(id)
			})
		},
		//打开详情窗口
		handleInfo(id) {
			this.formInfoVisible = true
			this.$nextTick(() => {
				this.$refs.formInfo.init(id)
			})
		},
		//删除
		handleDelete(row) {
			this.$confirm("确认删除该记录, 是否继续?", "提示", {
				confirmButtonText: "确定",
				cancelButtonText: "取消",
				type: "warning",
			})
				.then(() => {
					castleconfigmailDel(row.id).then(resp => {
						if (resp.code == 0) {
							this.$message({
								type: "success",
								message: "操作成功!",
							})
							//判断是否最后一页的最后一条记录
							let totalPages = (this.page.total - 1) % this.page.size == 0 ? (this.page.total - 1) / this.page.size : (this.page.total - 1) / this.page.size + 1
							if (this.page.current > totalPages && this.page.current != 1) {
								this.page.current = this.page.current - 1
							}
							this.queryList()
						} else {
							this.$msg({
								message: resp.msg,
								type: "error",
							})
						}
					})
				})
				.catch(() => {})
		},
		//批量删除
		handleDeleteBatch() {
			let checkedRow = this.$refs.multipleTable.selection
			if (checkedRow.length > 0) {
				let ids = []
				checkedRow.forEach(item => {
					ids.push(item.id)
				})
				this.$confirm("确认删除该记录, 是否继续?", "提示", {
					confirmButtonText: "确定",
					cancelButtonText: "取消",
					type: "warning",
				})
					.then(() => {
						castleconfigmailDelBatch(ids).then(resp => {
							if (resp.code == 0) {
								this.$message({
									type: "success",
									message: "操作成功!",
								})
								//判断是否最后一页的最后一条记录
								let totalPages = (this.page.total - checkedRow.length) % this.page.size == 0 ? (this.page.total - checkedRow.length) / this.page.size : (this.page.total - checkedRow.length) / this.page.size + 1
								if (this.page.current > totalPages && this.page.current != 1) {
									this.page.current = this.page.current - 1
								}
								this.queryList()
							} else {
								this.$msg({
									message: resp.msg,
									type: "error",
								})
							}
						})
					})
					.catch(() => {})
			} else {
				this.$msg({
					message: "请选择数据进行删除",
					type: "error",
				})
			}
		},
		//重置查询框
		resetQueryForm() {
			this.queryForm = {
				smtp: "",
				mail: "",
				status: "",
			}
			this.queryList({ current: 1 })
		},
		//切换查询条件收缩框
		handleCollapseState() {
			this.collapse.flag = !this.collapse.flag
			if (this.collapse.flag) {
				this.collapse.icon = "el-icon-arrow-up el-icon--right"
				this.collapse.label = "收起"
			} else {
				this.collapse.icon = "el-icon-arrow-down el-icon--right"
				this.collapse.label = "展开"
			}
		},
		//视图表格列表初始化
		initTableList() {
			viewTableList("castle_config_mail").then(resp => {
				if (resp.code == 0) {
					this.tableList = resp.data
					this.tableList.forEach(item => {
						this.tableShowList.push(item.propName)
					})
				}
			})
		},
		//状态 YesNo  yes启用，no禁用格式化返回
		statusFmt(row) {
			let name = ""
			if (this.YesNoList) {
				this.YesNoList.forEach(item => {
					if (item.code == row.status) {
						name = item.name
					}
				})
			}
			return name
		},
		//可见字段excel导出
		handleExport() {
			if (!this.tableShowList || this.tableShowList.length < 1) {
				this.$msg({
					message: "请选择要导出的列",
					type: "error",
				})
				return
			}
			let colNum = 1
			let headerList = []
			this.tableShowList.forEach(item => {
				let nameData = this.tableList.find(item2 => {
					return item2.propName == item
				})
				let name = ""
				if (nameData && nameData.propDesc) {
					name = nameData.propDesc
				} else {
					name = "未定义字段" + colNum++
				}
				headerList.push({ name: name, code: item })
			})
			castleconfigmailDynamicExport({
				headerList: headerList,
				dto: this.queryForm,
			})
		},

		handleDebug(code) {
			this.debug.visible = true
			this.debug.formData.code = code
		},
		cancelDeBug() {
			this.debug.visible = false
			this.debug.formData.code = ""
			this.debug.formData.subject = ""
			this.debug.formData.toUser = ""
			this.debug.formData.toCCUser = ""
			this.debug.formData.body = ""
			this.debug.formData.file = []
		},
		confirmDeBug() {
			this.loading = true
			let dd = {
				code: "",
				subject: "",
				toUser: "",
				toCCUser: "",
				body: "",
				file: [],
			}
			dd = {
				...dd,
				...this.debug.formData,
			}
			if (dd.toUser) {
				dd.toUser = dd.toUser.join(";")
			}
			if (dd.toCCUser) {
				dd.toCCUser = dd.toCCUser.join(";")
			}
			if (dd.file) {
				let fileUrls = []
				dd.file.forEach(item => {
					fileUrls.push(item.url)
				})
				dd.file = fileUrls
			}
			mailDebug(dd).then(resp => {
				if (resp.code == 0) {
					this.loading = false
					this.$message({
						type: "success",
						message: "操作成功!",
					})
					this.cancelDeBug()
				} else {
					this.$msg({
						message: resp.msg,
						type: "error",
					})
				}
			})
		},
		showUserInput() {
			this.debug.userValue = ""
			this.debug.userVisible = true
		},
		handleUserInputConfirm() {
			if (this.debug.userValue != "") {
				this.debug.formData.toUser.push(this.debug.userValue)
				this.debug.userValue = ""
			}
			this.debug.userVisible = false
		},
		handleUserClose(tag) {
			this.debug.formData.toUser = this.debug.formData.toUser.filter(item => item != tag)
		},
		showCCUserInput() {
			this.debug.userValue = ""
			this.debug.ccUserVisible = true
		},
		handleCCUserInputConfirm() {
			if (this.debug.ccUserValue != "") {
				this.debug.formData.toCCUser.push(this.debug.ccUserValue)
				this.debug.ccUserValue = ""
			}
			this.debug.ccUserVisible = false
		},
		handleCCUserClose(tag) {
			this.debug.formData.toCCUser = this.debug.formData.toCCUser.filter(item => item != tag)
		},
	},
}
</script>
<style scoped>
.el-tag {
	margin-right: 10px;
}
.input-new-tag {
	width: auto;
}
</style>
<style lang="scss">
.el-select-option-none {
	display: none !important;
}
.el-select-option-none-class {
	.el-input__suffix {
		display: none !important;
	}
}
</style>
